<script lang="ts">
import { Component, Inject, Prop, Vue, Watch } from 'vue-facing-decorator';
import UserLink from '@/pages/profile/component/UserLink.vue';
import type { CommentInfo, CommentListResponse } from '@/api/comment/comment';
import { getCommentsByChapterId, deleteComment, createComment } from '@/api/comment/comment';
import { type SimpleUserInfo, type UserInfo } from '@/api/auth/auth';
import { ElMessage, ElMessageBox } from 'element-plus';
import TextEditor from '@/components/editor/TextEditor.vue';
import dayjs from 'dayjs';

@Component({
  components: {
    UserLink,
    TextEditor,
  },
})
export default class CommentList extends Vue {
  declare $refs: {
    comment: HTMLDivElement[] | HTMLDivElement | undefined;
  };

  @Prop() cid!: number;
  @Prop() author!: SimpleUserInfo;
  @Inject() userInfo!: UserInfo;

  dayjs = dayjs;

  allComment: CommentListResponse | null = null;
  pageSize = 10;
  page = 1;
  get comments() {
    if (!this.allComment?.comments?.length) return [];
    return this.allComment.comments.slice((this.page - 1) * this.pageSize).slice(0, this.pageSize);
  }
  commentContent: string = '';

  async loadComments() {
    const resp = await getCommentsByChapterId(this.cid, 1, 1000);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }
    this.allComment = resp.data;
  }

  highlightCommentId: string | null = null;
  get queryCommentId() {
    const cid = this.$route.query.comment;
    return cid ? cid + '' : null;
  }
  @Watch('queryCommentId', { immediate: true })
  handleQueryCommentId() {
    if (this.queryCommentId) this.highlightCommentId = this.queryCommentId;
    this.$router.replace({
      name: this.$route.name,
      params: this.$route.params,
      query: { ...this.$route.query, cid: (void 0) },
    });
  }


  @Watch('allComment')
  @Watch('highlightCommentId')
  async highlightComment() {
    if (!this.allComment || !this.highlightCommentId) return;
    this.highlightCommentId = null;
    const index = this.allComment.comments.findIndex(comment => comment.id === +this.highlightComment!);
    if (index === -1) return;
    this.page = Math.ceil(index / this.pageSize) + 1;
    await this.$nextTick();
    const inPageIndex = index % this.pageSize;
    const commentElements = Array.isArray(this.$refs.comment) ? this.$refs.comment : this.$refs.comment ? [this.$refs.comment] : [];
    const commentElement = commentElements[inPageIndex];
    if (!commentElement) return;
    commentElement.scrollIntoView({ behavior: 'smooth' });
    commentElement.classList.add('highlight-comment');
    setTimeout(() => {
      commentElement.classList.remove('highlight-comment');
    }, 3e3);
  }

  async deleteComment(commentId: number) {
    const cont = await ElMessageBox.confirm('确定要删除这条评论吗？此操作不可恢复。', '删除评论', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => true, () => false);
    if (!cont) return;
    const resp = await deleteComment(commentId);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }
    ElMessage({ type: 'success', message: '评论已删除' });
    this.loadComments();
  }

  async submitComment() {
    if (!this.commentContent.trim()) {
      ElMessage({ type: 'warning', message: '评论内容不能为空' });
      return;
    }
    const content = this.commentContent;
    this.commentContent = '';
    const resp = await createComment(this.cid, content);
    if (resp.error != null) {
      ElMessage({ type: 'error', message: resp.error });
      this.commentContent = content;
      return;
    }
    ElMessage({ type: 'success', message: '评论提交成功' });
    await this.loadComments();
    this.highlightCommentId = resp.data.id;
  }

  get mayAddComment() {
    return this.userInfo != null;
  }
  mayDeleteComment(comment: CommentInfo) {
    if (!this.userInfo) return false;
    const isCommentAuthor = comment.author.id === this.userInfo.id;
    const isAdmin = this.userInfo.role === 'admin';
    const isMod = this.userInfo.role === 'mod';
    const isNovelAuthor = this.author.id === this.userInfo.id;
    const isCommentByAdmin = comment.author.role === 'admin';
    return isCommentAuthor || (isAdmin || isMod || isNovelAuthor) && !isCommentByAdmin;
  }

  getAvatarUrl(avatar: string | undefined | null) {
    if (!avatar) return './img/avatar.png';
    return '/api/image/' + avatar;
  }

  @Watch('cid', { immediate: true })
  onCidChange() {
    this.loadComments();
  }

}
</script>
<template>
  <div class="comment-list">
    <h3>评论区</h3>
    <div class="comment-area" v-if="mayAddComment">
      <text-editor v-model="commentContent" />
      <div class="comment-action-row">
        <el-button class="comment-submit-button" type="primary" @click="submitComment">提交评论</el-button>
      </div>
    </div>
    <div v-if="comments.length > 0" class="comments-container">
      <div v-for="comment in comments" :key="comment.id" class="comment-item" :id="'comment-' + comment.id" ref="comment">
        <user-link :user="comment.author" class="comment-avatar">
          <img width="40" height="40" :src="getAvatarUrl(comment.author.avatar)" :alt="comment.author.name" class="user-avatar" />
        </user-link>
        <div class="comment-header">
          <div v-if="mayDeleteComment(comment)" class="comment-actions">
            <el-dropdown placement="bottom-end">
              <el-button icon="el-icon-more"></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="deleteComment(comment.id)"><span class="danger-item">删除评论</span></el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="comment-user"><user-link :user="comment.author"></user-link></div>
          <div class="comment-time">{{ dayjs(comment.created_at).format('YYYY-MM-DD HH:mm:ss') }}</div>
        </div>
        <div class="comment-content">
          <text-editor :model-value="comment.content" readonly />
        </div>
      </div>
    </div>
    <el-pagination v-if="allComment?.total && allComment?.total > pageSize"
      v-model:current-page="page" :page-size="pageSize" :total="allComment.total" layout="prev, pager, next" />
    <div v-else class="no-comments">
      <span v-if="mayAddComment">还没有评论，赶快发表第一条评论吧</span>
      <span v-else>还没有评论，注册一个账号，发表评论吧</span>
    </div>
  </div>
</template>
<style scoped>

.comment-action-row {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  vertical-align: middle;
}
.user-avatar-link {
  display: inline-block;
}

.user-name {
  margin-right: 10px;
  font-weight: bold;
  color: #409EFF;
  text-decoration: none;
}
.user-name:hover {
  text-decoration: underline;
}

.comment-item {
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  padding: 15px;
  margin-bottom: 15px;
  position: relative;
  display: grid;
  grid-template: "avatar header" "content content";
  grid-template-columns: auto 1fr;
  grid-template-rows: auto 1fr;
}

.comment-avatar {
  grid-area: avatar;
}

.comment-header {
  grid-area: header;
}

.comment-content {
  grid-area: content;
  padding: 10px 0;
}

.comment-content :deep(.editor-wrap .editor-container),
.comment-content :deep(.editor-wrap .editor-container .milkdown > .editor) {
  min-height: auto;
  padding: 0;
  background: none;
}

.comment-user {
  display: block;
}

.comment-time {
  color: var(--el-text-color-secondary);
}

.comment-actions {
  float: right;
}

.danger-item {
  color: var(--el-color-danger);
}

.highlight-comment {
  animation: highlight 3s ease-out;
}

@keyframes highlight {
  0% {
    background-color: rgba(255, 255, 0, 0.3);
  }
  100% {
    background-color: transparent;
  }
}

.no-comments {
  color: var(--el-text-color-secondary);
  text-align: center;
  padding: 20px 0;
}
</style>
